﻿using System.Collections.Generic;
using System;

using System.IO;
using SocialFilter.model;
using System.Xml;

namespace SocialFilter.controller
{
	class RSSController
	{
		// Take in Items and spit out feeds
		public bool generateFeed(Feed _feed, string _feedDirectory)
		{
			if ( _feed.Items == null )
			{
				return false;
			}
			if ( _feed.Accounts.Count == 0 )
			{
				return false;
			}
			string userName = _feed.Accounts[0].AccountName;
			string siteName = _feed.Accounts[0].SiteName;
			
			
			try
			{
				XmlElement channel = generateRSSSkeleton(userName, _feed.FeedName);
				
				//Only include the top X items, sorted by publish date
				_feed.Items.Sort();
				int maxItems;
				 if (!int.TryParse( ConfigurationController.GetConfiguration("max_feed_items"), out maxItems ))
				 {
					maxItems = 100;
				 }
				 maxItems = Math.Min(maxItems, _feed.Items.Count);
				
				
				for (int i = 0; i < maxItems; ++i)
				{
					// Write content from _items to channel
					channel.AppendChild(generateRSSItem(_feed.Items[i], channel.OwnerDocument));
				}				

				//TODO: if no file exists, create a php script w/ matching name, this php script will try to access the rss file
				// this will allow us to lock control of the file properly
				// the php script must also try to lock the file
				string feedURN =  _feed.Url;
				string feedPath = _feedDirectory + "/" + feedURN;
				FileStream fs = new FileStream(feedPath, FileMode.Create, FileAccess.Write, FileShare.None);
				channel.OwnerDocument.Save(fs);
				fs.Close();
				return true;
			}
			catch (Exception e)
			{
				Console.WriteLine("An error occurred while generating feed: " + e.Message);
				return false;
			}
		}

		private XmlElement generateRSSSkeleton(string _username, string _feedName)
		{
			XmlDocument rssFeed = new XmlDocument();
			// Create rss layout
			// For details on the RSS spec, see http://www.rgagnon.com/javadetails/java-0556.html
			XmlElement root = rssFeed.CreateElement("rss");
			root.SetAttribute("version", "2.0");
			rssFeed.AppendChild(root);
			XmlElement channel = rssFeed.CreateElement("channel");
			root.AppendChild(channel);
			XmlElement title = rssFeed.CreateElement("title");
			title.InnerText = _feedName;
			channel.AppendChild(title);
			XmlElement description = rssFeed.CreateElement("description");
			description.InnerText = "A custom feed from " + _username;
			channel.AppendChild(description);
			XmlElement link = rssFeed.CreateElement("link");
			//TODO generate link
			channel.AppendChild(link);

			return channel;
		}
		
		private XmlElement generateRSSItem( FeedItem _feedItem, XmlDocument _document )
		{
			XmlElement item = _document.CreateElement("item");
			XmlElement title = _document.CreateElement("title");
			title.InnerText = "From " + _feedItem.Source;
			item.AppendChild(title);
			XmlElement link = _document.CreateElement("link");
			link.SetAttribute("href", _feedItem.Link);
			item.AppendChild(link);
			XmlElement author = _document.CreateElement("author");
			author.InnerText = _feedItem.Author;
			item.AppendChild(author);
			XmlElement pubDate = _document.CreateElement("pubDate");
			pubDate.InnerText = _feedItem.TimeStamp.ToString("dddd, dd MMMM yyyy - h:mm tt");
			item.AppendChild(pubDate);
			XmlElement content = _document.CreateElement("content");
			content.InnerText = _feedItem.Content;
			item.AppendChild(content);
			return item;
		}
	}
}
